import { NextRequest, NextResponse } from 'next/server';
import jwt from 'jsonwebtoken';
import argon2 from 'argon2';
import User from '@/models/user';
import { LoginRequest, LoginResponse, ApiResponse } from '@/types/interface';

export async function POST(request: NextRequest) {
  try {
    const body: LoginRequest = await request.json();
    const { username, password } = body;

    // 根据用户名查找用户
    const user: any = await User.findOne({
      where: { username },
      attributes: ['id', 'username', 'password_hash', 'email'],
      raw: true, // 使用raw: true返回普通对象，避免Sequelize模型实例的访问问题
    });
    
    // 检查用户是否存在
    if (!user) {
      return NextResponse.json(
        { code: 401, msg: '用户名或密码错误', data: null },
        { status: 401 }
      );
    }

    // 验证密码
    if (!password || !user.password_hash) {
      return NextResponse.json(
        { code: 401, msg: '用户名或密码错误', data: null },
        { status: 401 }
      );
    }
    
    const isPasswordValid = await argon2.verify(user.password_hash, password);
    if (!isPasswordValid) {
      return NextResponse.json(
        { code: 401, msg: '用户名或密码错误', data: null },
        { status: 401 }
      );
    }

    const secret = process.env.JWT_SECRET;
    if (!secret) {
      return NextResponse.json(
        { code: 500, msg: '服务器配置错误', data: null },
        { status: 500 }
      );
    }

    // 生成JWT令牌
    const token = jwt.sign(
      { 
        id: user.id.toString(), 
        username: user.username, 
        email: user.email,
        roles: ['user'] // 默认角色，可以根据实际需求扩展
      },
      secret,
      { expiresIn: '24h' }
    );

    const response: ApiResponse<LoginResponse> = {
      code: 200,
      msg: '登录成功',
      data: {
        access_token: token,
        token_type: 'Bearer',
        user: {
          id: user.id.toString(),
          username: user.username,
          roles: ['user']
        }
      }
    };

      const nextResponse = NextResponse.json(response);
      
      // 设置cookie
      nextResponse.cookies.set('token', token, {
        httpOnly: true,
        secure: process.env.NODE_ENV === 'production',
        sameSite: 'lax',
        maxAge: 24 * 60 * 60 // 24小时
      });

      return nextResponse;
  } catch (error) {
    console.error('Login error:', error);
    return NextResponse.json(
      { code: 500, msg: '服务器内部错误', data: null },
      { status: 500 }
    );
  }
}
